using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace Lib.Tools.Serializations
{
    public class BinarySerialization
    {
        public static void Serializer<T>(T entity, string filePath)
        {
            using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fileStream, entity);
                fileStream.Close();
            }
        }
        public static MemoryStream Serializer<T>(T entity)
        {
            MemoryStream stream = new MemoryStream();
            BinaryFormatter formatter = new BinaryFormatter();
            formatter.Serialize(stream, entity);
            stream.Flush();
            stream.Position = 0;
            return stream;

        }
        public static T UnSerializer<T>(MemoryStream stream)
        {
            T entity = default(T);
            BinaryFormatter formatter = new BinaryFormatter();
            entity = (T)formatter.Deserialize(stream);
            return entity;
        }
        public static T UnSerializer<T>(string filePath)
        {
            T entity = default(T);
            using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                entity = (T)formatter.Deserialize(fileStream);
                fileStream.Close();
            }
            return entity;
        }

    }
}
